import { Component, ElementRef, Input, NgZone, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { fromEvent, Subscription, takeUntil } from 'rxjs';

import { InfiniteScrollCustomEvent } from '@ionic/angular';

import { ChannelService } from '@/core/services/channel/channel.service';
import { BaseComponent } from '@/shared/components/base.component';

@Component({
  selector: 'app-channel-rollltable',
  templateUrl: './channel-rolltable.component.html'
})
export class CahnnelRolltableComponent extends BaseComponent implements OnInit {
  isLocal = this.route.snapshot.data.title === '渠道';

  @ViewChild('headerDetail', { static: true })
  headerDetail!: ElementRef<HTMLDivElement>;

  @ViewChild('detaillList', { static: true })
  detaillList!: ElementRef<HTMLDivElement>;

  @Input()
  set bsDateRange(value: string) {
    this.salesRankingJson.date = value;
    this.getSalesRankingInfoList();
  }

  private salesRankingJson: {
    pageSize: number;
    pageIndex: number;
    date: string;
  } = {
    pageIndex: 1,
    pageSize: 10,
    date: '0'
  };

  detailUrl?: string;

  salesRankingInfoList?: ReadonlyArray<Record<string, unknown>>;

  salesRankingTotal?: number;

  private salesRankingSub?: Subscription = new Subscription();

  constructor(private channelService: ChannelService, private ngZone: NgZone, private route: ActivatedRoute) {
    super();
  }

  ngOnInit() {
    this.initSubscribe();
  }

  initSubscribe() {
    this.subscribeListScroll();
  }

  subscribeListScroll() {
    const el = this.detaillList.nativeElement;
    const target = this.headerDetail.nativeElement;
    fromEvent(el, 'scroll')
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(() => {
        this.ngZone.runOutsideAngular(() => {
          target.scrollLeft = el.scrollLeft;
        });
      });
  }

  getSalesRankingInfoList(event?: any) {
    this.salesRankingSub?.unsubscribe();
    event = event as InfiniteScrollCustomEvent;
    if (event) {
      this.salesRankingJson.pageIndex += 1;
    }
    this.salesRankingSub = this.channelService.getSalesRankingInfoList().subscribe({
      next: rsp => {
        this.detailUrl = this.isLocal
          ? `/wholemarket/overview?overviewTab=toBeIssued&date=${this.salesRankingJson.date}`
          : '';

        this.salesRankingTotal = rsp.total;
        this.salesRankingInfoList = !this.salesRankingInfoList
          ? rsp.returnList
          : [...this.salesRankingInfoList, ...rsp.returnList];
        if (event && this.salesRankingInfoList.length === this.salesRankingTotal) {
          event.target.disabled = true;
        }
        event?.target.complete();
      },
      error: error => {
        this.errorService.error(error);
        event?.target.complete();
      }
    });
  }

  async ionViewWillLeave() {
    this.unsubscribeSalesRankingSub();
  }

  unsubscribeSalesRankingSub() {
    if (!this.salesRankingSub?.closed) {
      this.salesRankingSub?.unsubscribe();
    }
  }

  trackSalesRankingDetailList(index: number, item: any) {
    return item;
  }
}
